package com.zyx.springredispub.config;

import com.zyx.springredispub.cons.Channels;
import com.zyx.springredispub.service.RedisReceiver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @author zyx
 * @since 2022/3/30 23:33
 * desc: redis发布订阅消息相关配置
 */
@Configuration
public class RedisConfig {
    /** 初始化监听器 */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter firstCh,
                                            MessageListenerAdapter secondCh) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 每条消息都需要从相同或不同的管道进入，此处只配置一个管道，如果需要多个消息订阅处理，则需要配置多个
        container.addMessageListener(firstCh, new PatternTopic(Channels.CH01.getChName()));
        container.addMessageListener(secondCh, new PatternTopic(Channels.CH02.getChName()));
        return container;
    }

    @Bean
    MessageListenerAdapter firstCh(RedisReceiver redisReceiver) {
        // 指定的对象，RedisReceiver
        // 指定对象中的指定处理方法 first 对应 RedisReceiver 类中的 first(String message)
        return new MessageListenerAdapter(redisReceiver, Channels.CH01.getRecName());
    }

    @Bean
    MessageListenerAdapter secondCh(RedisReceiver redisReceiver) {
        // 指定的对象，RedisReceiver
        // 指定对象中的指定处理方法 second 对应 RedisReceiver 类中的 second(String message)
        return new MessageListenerAdapter(redisReceiver, Channels.CH02.getRecName());
    }
}
